// 后端API服务 - 基于axios的封装版本
import axios from 'axios';
import {ElMessage} from 'element-plus';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8081/api';

// 创建axios实例
const apiClient = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: false, // 启用credentials以支持JWT token
});

// 统一响应格式封装
class ApiResponse {
    constructor(success, data, message = '', code = 200, timestamp = Date.now()) {
        this.success = success;
        this.data = data;
        this.message = message;
        this.code = code;
        this.timestamp = timestamp;
    }

    static success(data, message = '操作成功') {
        return new ApiResponse(true, data, message);
    }

    static error(message = '操作失败', code = 500, data = null) {
        return new ApiResponse(false, data, message, code);
    }

    toJSON() {
        return {
            success: this.success,
            data: this.data,
            message: this.message,
            code: this.code,
            timestamp: this.timestamp
        };
    }
}

// 请求拦截器
apiClient.interceptors.request.use(
    (config) => {
        // 添加认证token
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        // 添加时间戳
        config.headers['X-Request-Timestamp'] = Date.now();

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
apiClient.interceptors.response.use(
    (response) => {
        const { data } = response
        // 后端返回格式: { success: boolean, code: number, message: string, data: object }
        if(data.success || data.code === 200){
            return data
        }else{
            return Promise.reject(new Error(data.message || '请求失败'))
        }
       
    },
    (error) => {
        console.error('API请求错误:', error);

        // 处理HTTP错误
        if (error.response) {
            const apiResponse = error.response.data;

            // 处理认证错误
            if (error.response.status === 403) {
                localStorage.removeItem('token');
                ElMessage.error('登录已过期，请重新登录');
                window.location.href = '/login';
                return Promise.reject(error);
            }

            // 显示错误消息
            const errorMessage = apiResponse?.message || error.message || '请求失败';
            ElMessage.error(errorMessage);

            // 返回统一错误格式
            const errorResponse = ApiResponse.error(
                errorMessage,
                apiResponse?.code || error.response.status,
                apiResponse?.data
            ).toJSON();

            return Promise.reject(errorResponse);
        }

        // 网络错误或其他错误
        const errorMessage = error.message || '网络连接失败';
        ElMessage.error(errorMessage);

        const networkError = ApiResponse.error(
            errorMessage,
            -1
        ).toJSON();

        return Promise.reject(networkError);
    }
);

// 常用HTTP方法封装
const http = {
    async get(endpoint, params = {}, showError = false) {
        try {
            const result = await apiClient.get(endpoint, {params});
            if (showError && result.code !== 200) {
                ElMessage.success(result.message || '请求失败');
            }
            return result;
        } catch (error) {
            if (showError) {
                ElMessage.error(error.message || '请求失败');
            }
            throw error;
        }
    },

    async post(endpoint, data = {}, config = {}, showError = false) {
        try {
            const result = await apiClient.post(endpoint, data, config);
            if (showError && result.code !== 200) {
                ElMessage.success(result.message || '请求失败');
            }
            return result;
        } catch (error) {
            if (showError) {
                ElMessage.error(error.message || '请求失败');
            }
            throw error;
        }
    },

    async put(endpoint, data = {}, showError = false) {
        try {
            const result = await apiClient.put(endpoint, data);
            if (showError && result.code !== 200) {
                ElMessage.success(result.message || '请求失败');
            }
            return result;
        } catch (error) {
            if (showError) {
                ElMessage.error(error.message || '请求失败');
            }
            throw error;
        }
    },

    async patch(endpoint, data = {}) {
        return apiClient.patch(endpoint, data);
    },

    async delete(endpoint, data = {}, config = {}, showError=false) {
        try {
            const result = await apiClient.delete(endpoint, {data, ...config});
            if (showError && result.code !== 200) {
                ElMessage.success(result.message || '请求失败');
            }
            return result;
        } catch (error) {
            if (showError) {
                ElMessage.error(error.message || '请求失败');
            }
            throw error;
        }
    },

    async upload(endpoint, formData) {
        return apiClient.post(endpoint, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
    },
};

// 认证相关API
export const authAPI = {
    async login(credentials) {
        return http.post('/auth/login', credentials);
    },

    async register(userData) {
        return http.post('/auth/register', userData);
    },

    async resetPassword(email) {
        return http.post('/auth/reset-password', {email});
    },

    async getProfile() {
        return http.get('/auth/profile');
    },

    async updateProfile(updates) {
        return http.put('/auth/profile', updates);
    },
};

// 电影相关API
export const movieAPI = {
    async getMovies(params = {}) {
        return http.get('/movies', params);
    },

    async getAllMovies() {
        return http.get('/movies/all');
    },

    async getMovie(id) {
        return http.get(`/movies/${id}`);
    },

    async createMovie(movieData) {
        return http.post('/movies', movieData);
    },

    async updateMovie(id, movieData) {
        return http.put(`/movies/${id}`, movieData);
    },

    async deleteMovie(id) {
        return http.delete(`/movies/${id}`);
    },

    async searchMovies(keyword) {
        return http.get('/movies/search', {keyword});
    },

    async getMoviesByCategory(categoryId) {
        return http.get(`/movies/category/${categoryId}`);
    },

    async getCategories() {
        return http.get('/categories');
    },

    async getCategoriesByType(type) {
        return http.get(`/categories/type/${type}`);
    },

    async getActiveCategoriesByType(type) {
        return http.get(`/categories/active/type/${type}`);
    },
};

// 用户相关API - 基于后端新创建的接口
export const userAPI = {
    // 收藏相关API
    async getFavorites(userId) {
        return http.get('/user/favorites', {userId});
    },

    async addFavorite(userId, movieId) {
        return http.post('/user/favorites', {userId, movieId});
    },

    async removeFavorite(userId, movieId) {
        return http.delete('/user/favorites', {userId, movieId});
    },
    async removeBatchFavorite(params) {
        return http.delete('/user/favorites/batch', params);
    },

    async isFavorite(userId, movieId) {
        return http.get('/user/favorites/check', {userId, movieId});
    },

    async countFavorites(userId) {
        return http.get('/user/favorites/count', {userId});
    },

    // 观看历史相关API
    async getWatchHistory(userId) {
        return http.get('/user/history', {userId});
    },

    async getRecentWatchHistory(userId) {
        return http.get('/user/history/recent', {userId});
    },

    async addToHistory(userId, movieId, watchTime = 0, lastPosition = null) {
        return http.post('/user/history', {
                userId, movieId, watchTime, lastPosition
            }
        );
    },

    async deleteHistory(userId, id) {
        return http.delete(`/user/history`, {userId,id});
    },

    async clearHistory(userId) {
        return http.delete('/user/history', {userId});
    },

    async countWatchHistory(userId) {
        return http.get('/user/history/count', {userId});
    },

    // 评分相关API
    async getRatings(userId) {
        return http.get('/user/ratings', {userId});
    },

    async getMovieRatings(movieId, userId) {
        return http.get(`/user/ratings/movie/${movieId}`, {userId});
    },

    async setRating(userId, movieId, rating, comment = '') {
        return http.post('/user/ratings', {
            userId, movieId, rating, comment
        });
    },

    async removeRating(userId, movieId) {
        return http.delete('/user/ratings', {userId, movieId});
    },

    async hasRated(userId, movieId) {
        return http.get('/user/ratings/check', {userId, movieId});
    },

    async getUserRatingForMovie(userId, movieId) {
        return http.get('/user/ratings/user-movie', {userId, movieId});
    },

    async getMovieAverageRating(movieId) {
        return http.get(`/user/ratings/movie/${movieId}/average`);
    },

    async countMovieRatings(movieId) {
        return http.get(`/user/ratings/movie/${movieId}/count`);
    }
};

// 资讯相关API
export const newsAPI = {
    // 获取资讯列表
    async getNewsList(params = {}) {
        return http.get('/news', params);
    },

    // 获取资讯详情
    async getNewsDetail(id) {
        return http.get(`/news/${id}`);
    },

    // 搜索资讯
    async searchNews(keyword, params = {}) {
        return http.get('/news/search', { keyword, ...params });
    },

    // 获取热门资讯
    async getHotNews(limit = 5) {
        return http.get('/news/hot', { limit });
    },

    // 获取置顶资讯
    async getTopNews() {
        return http.get('/news/top');
    },

    // 获取最新资讯
    async getLatestNews(limit = 5) {
        return http.get('/news/latest', { limit });
    },

    // 获取分类列表
    async getActiveCategoriesByType(type) {
        return http.get(`/categories/active/type/${type}`);
    }
};

// 评论相关API
export const commentAPI = {
    async getComments(movieId) {
        return http.get(`/movies/${movieId}/comments`);
    },

    async addComment(movieId, content) {
        return http.post(`/movies/${movieId}/comments`, {content});
    },

    async deleteComment(commentId) {
        return http.delete(`/comments/${commentId}`);
    },
};

// 工具函数
export const apiUtils = {
    // 设置基础URL
    setBaseURL(baseURL) {
        apiClient.defaults.baseURL = baseURL;
    },

    // 获取当前token
    getToken() {
        return localStorage.getItem('token');
    },

    // 设置token
    setToken(token) {
        localStorage.setItem('token', token);
        // 更新axios实例的默认headers
        if (token) {
            apiClient.defaults.headers.Authorization = `Bearer ${token}`;
        } else {
            delete apiClient.defaults.headers.Authorization;
        }
    },

    // 清除token
    clearToken() {
        localStorage.removeItem('token');
        delete apiClient.defaults.headers.Authorization;
    },

    // 检查是否已认证
    isAuthenticated() {
        return !!localStorage.getItem('token');
    },

    // 添加自定义请求头
    setHeader(key, value) {
        apiClient.defaults.headers[key] = value;
    },

    // 移除自定义请求头
    removeHeader(key) {
        delete apiClient.defaults.headers[key];
    },
};

// 导出axios实例以便自定义配置
export {apiClient};

export default {
    auth: authAPI,
    movie: movieAPI,
    user: userAPI,
    comment: commentAPI,
    news: newsAPI,
    utils: apiUtils,
    http,
    client: apiClient,
};